﻿using System;
using System.Web;
using System.Web.Mvc;
using System.Text;
using EzDesk.Core.ServiceImpl.Services;
using EzDesk.Utility.Extensions;
using EzDesk.Utility.Web.Extensions;

namespace EzDesk.ServiceHost.Controllers
{
    public class EzAuthContext
    {
        public bool IsAuthrized
        {
            get { return IdentityId.HasValue; }
        }

        public Guid? IdentityId { get; set; }
    }

    public class JsonExResult : JsonResult
    {
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            HttpResponseBase response = context.HttpContext.Response;

            if (!String.IsNullOrEmpty(ContentType))
            {
                response.ContentType = ContentType;
            }
            else
            {
                response.ContentType = "application/json";
            }
            if (ContentEncoding != null)
            {
                response.ContentEncoding = ContentEncoding;
            }
            if (Data != null)
            {
                response.Write(Data.ToJson());
            }
        }
    }

    public class EzAuthorizeAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var ezdeskController = filterContext.Controller as EzDeskController;
            if (ezdeskController == null) return;
            try
            {
                // 在这个地方，尝试找到传过来的ez_auth_token并且去获取相应的IdentityName
                var ez_auth_toke = filterContext.HttpContext.Request["ez_auth_token"];
                if (!string.IsNullOrEmpty(ez_auth_toke))
                {
                    var userId = ezdeskController.TokenService.GetUserIdByToken(ez_auth_toke);
                    ezdeskController.AuthContent.IdentityId = userId;
                }
                base.OnActionExecuting(filterContext);
            }catch(Exception ex)
            {
                var result = new {auth = 0};
                //验证错误
                filterContext.Result = new JsonResult()
                                           {
                                               Data = result,
                                               JsonRequestBehavior = JsonRequestBehavior.AllowGet
                                           };
            }
        }
    }

    public class EzDeskController : Controller
    {

        public ClientTokenService TokenService = new ClientTokenService();

        private readonly EzAuthContext _authContent = new EzAuthContext();
        public EzAuthContext AuthContent
        {
            get { return _authContent; }
        }
        
        protected Guid CurrentUserId
        {
            get
            {
                if (!AuthContent.IdentityId.HasValue)
                {
                    throw new Exception("你还没有身份验证");
                }
                return AuthContent.IdentityId.Value;
            }
        }
        
        protected override void OnResultExecuting(ResultExecutingContext filterContext)
        {
            Response.AddHeader("Access-Control-Allow-Origin", "*");
            Response.AddHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
            base.OnResultExecuting(filterContext);
        }

        protected override JsonResult Json(object data, string contentType, Encoding contentEncoding, JsonRequestBehavior behavior)
        {
            JsonResult result = base.Json(data, contentType, contentEncoding, behavior);
            JsonExResult resultEx = new JsonExResult()
            {
                ContentEncoding = result.ContentEncoding,
                ContentType = result.ContentType,
                Data = result.Data,
                JsonRequestBehavior = result.JsonRequestBehavior
            };
            return resultEx;
        }

        protected string getEpochForJavascript(DateTime dateTime)
        {
            return string.Format("'{0}'", dateTime.ToEpoch());
        }

        protected virtual ActionResult ReturnView(string r, string txtInfo, object routeValues)
        {
            SetReturnInfoText(txtInfo);
            return View(routeValues);
        }

        protected ActionResult ReturnView(string actionName, string controllerName, string txtInfo, object routeValues)
        {
            SetReturnInfoText(txtInfo);
            return RedirectToAction(actionName, controllerName, routeValues);
        }

        protected void SetReturnInfoText(string txtInfo)
        {
            TempData["txtInfo"] = txtInfo;
        }



    }

}
